// src/pages/Home/DataSourceManagement/RealTimeDataUpdate.jsx
import React, { useState, useEffect } from 'react';
import {
  Card, Button, Switch, List, Tag, Alert,
  Space, Timeline, Row, Col, Statistic, Progress
} from 'antd';
import {
  SyncOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined
} from '@ant-design/icons';

const RealTimeDataUpdate = () => {
  const [realTimeEnabled, setRealTimeEnabled] = useState(false);
  const [updateLogs, setUpdateLogs] = useState([]);
  const [connectionStatus, setConnectionStatus] = useState('disconnected');
  const [stats, setStats] = useState({
    totalUpdates: 0,
    successUpdates: 0,
    failedUpdates: 0,
    lastUpdate: null
  });

  // 模拟实时数据更新
  useEffect(() => {
    if (!realTimeEnabled) return;

    setConnectionStatus('connecting');

    // 模拟连接建立
    const connectTimer = setTimeout(() => {
      setConnectionStatus('connected');
    }, 1000);

    // 模拟数据更新
    const interval = setInterval(() => {
      const now = new Date();
      const timeStr = now.toLocaleTimeString();

      const updateTypes = [
        '数据表 users 已更新，新增5条记录',
        '数据表 orders 已更新，新增3条记录',
        '数据表 products 价格字段已批量更新',
        '从分析数据库刷新了销售分析数据',
        '数据表 customers 联系信息已更新'
      ];

      const isSuccess = Math.random() > 0.2; // 80% 成功率

      const newLog = {
        id: Date.now(),
        time: timeStr,
        message: updateTypes[Math.floor(Math.random() * updateTypes.length)],
        status: isSuccess ? 'success' : 'failed',
        timestamp: now
      };

      setUpdateLogs(prev => [newLog, ...prev.slice(0, 19)]); // 保留最近20条记录

      setStats(prev => ({
        totalUpdates: prev.totalUpdates + 1,
        successUpdates: isSuccess ? prev.successUpdates + 1 : prev.successUpdates,
        failedUpdates: isSuccess ? prev.failedUpdates : prev.failedUpdates + 1,
        lastUpdate: timeStr
      }));
    }, 5000);

    return () => {
      clearTimeout(connectTimer);
      clearInterval(interval);
      setConnectionStatus('disconnected');
    };
  }, [realTimeEnabled]);

  const handleToggleRealTime = (enabled) => {
    setRealTimeEnabled(enabled);
    if (!enabled) {
      setUpdateLogs([]);
      setStats({
        totalUpdates: 0,
        successUpdates: 0,
        failedUpdates: 0,
        lastUpdate: null
      });
    }
  };

  const getConnectionStatusTag = () => {
    switch (connectionStatus) {
      case 'connected':
        return <Tag icon={<CheckCircleOutlined />} color="success">已连接</Tag>;
      case 'connecting':
        return <Tag icon={<SyncOutlined spin />} color="processing">连接中</Tag>;
      case 'disconnected':
        return <Tag icon={<CloseCircleOutlined />} color="error">已断开</Tag>;
      default:
        return <Tag>未知</Tag>;
    }
  };

  const clearLogs = () => {
    setUpdateLogs([]);
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title={
          <Space>
            <SyncOutlined />
            实时数据更新
          </Space>
        }
        extra={
          <Space>
            {getConnectionStatusTag()}
            <Switch
              checked={realTimeEnabled}
              onChange={handleToggleRealTime}
              checkedChildren="启用"
              unCheckedChildren="禁用"
              loading={connectionStatus === 'connecting'}
            />
          </Space>
        }
      >
        <Alert
          message="实时数据更新功能"
          description="开启后，系统将通过WebSocket实时接收数据变更通知，并自动刷新相关数据。"
          type="info"
          showIcon
          style={{ marginBottom: 24 }}
        />

        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="总更新次数"
                value={stats.totalUpdates}
                prefix={<SyncOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="成功更新"
                value={stats.successUpdates}
                valueStyle={{ color: '#3f8600' }}
                prefix={<CheckCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="失败更新"
                value={stats.failedUpdates}
                valueStyle={{ color: '#cf1322' }}
                prefix={<CloseCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="最后更新"
                value={stats.lastUpdate || '无'}
              />
            </Card>
          </Col>
        </Row>

        <Card
          title="实时更新日志"
          extra={
            <Space>
              <Button size="small" onClick={clearLogs}>清空日志</Button>
            </Space>
          }
        >
          {updateLogs.length > 0 ? (
            <List
              dataSource={updateLogs}
              renderItem={item => (
                <List.Item>
                  <List.Item.Meta
                    avatar={
                      item.status === 'success' ?
                        <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '16px' }} /> :
                        <CloseCircleOutlined style={{ color: '#ff4d4f', fontSize: '16px' }} />
                    }
                    title={
                      <Space>
                        <span>[{item.time}]</span>
                        <Tag color={item.status === 'success' ? 'success' : 'error'}>
                          {item.status === 'success' ? '成功' : '失败'}
                        </Tag>
                      </Space>
                    }
                    description={item.message}
                  />
                </List.Item>
              )}
            />
          ) : (
            <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
              <ClockCircleOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
              <p>暂无实时更新日志</p>
              <p style={{ fontSize: '12px' }}>
                {realTimeEnabled
                  ? '等待数据更新...'
                  : '请启用实时数据更新功能以查看日志'}
              </p>
            </div>
          )}
        </Card>
      </Card>
    </div>
  );
};

export default RealTimeDataUpdate;
